package com.youdoneed.news.news.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.GsonUtils;
import com.youdoneed.base.common.OkHttpUtils;
import com.youdoneed.community.feign.ForumClient;
import com.youdoneed.community.forum.entity.Forumcomment;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.news.common.config.AppConfig;
import com.youdoneed.news.common.util.StringUUIdUtil;
import com.youdoneed.news.news.dao.*;
import com.youdoneed.news.news.entity.*;
import com.youdoneed.news.news.vo.*;
import com.youdoneed.user.feign.UserFeignClient;
import com.youdoneed.user.model.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

@Service
public class CmfPostsService {

    private final Logger logger = LoggerFactory.getLogger(CmfPostsService.class);

    /**
     * 热评新闻
     */
    private static final String HOT_COMMENT_NEWS = "15xybv380tfsawkacdjz";
    /**
     * 趣闻推荐
     */
    private static final String JOKE_RECOMMENEDE = "15xybk28n7wt6l5rk90a";
    /**
     * 未关注
     */
    private static final String NO_FOCUS = "0";
    /**
     * 已关注
     */
    private static final String IS_FOCUS = "1";
    @Autowired
    private CmfPostsMapper cmfPostsMapper;
    @Autowired
    private FriendsClient friendsClient;
    @Autowired
    private CmfTermRelationshipsMapper cmfTermRelationshipsMapper;
    @Autowired
    private CmfTermsMapper cmfTermsMapper;
    @Autowired
    private CmfAuthorsMapper cmfAuthorsMapper;
    @Autowired
    private CmfAuthorService cmfAuthorService;
    @Autowired
    private ForumClient forumClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CmfAuthorFocusMapper cmfAuthorFocusMapper;
    @Autowired
    private CmfPostShieldMapper cmfPostShieldMapper;
    @Autowired
    private CmfNavMapper cmfNavMapper;
    @Autowired
    private CmfPostsReadlogMapper cmfPostsReadlogMapper;
    @Autowired
    private CmfLabelRelationMapper cmfLabelRelationMapper;
    @Autowired
    private CmfAuthorWeightMapper cmfAuthorWeightMapper;
    @Autowired
    private CmfLabelMapper cmfLabelMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AppConfig appConfig;

    /**
     * 获取好友浏览过的新闻列表
     *
     * @return
     * @throws ParseException
     * @throws NumberFormatException
     * @author hexz
     * @date 2017.7.3
     */
    public List<CmfPostsListOfFriends> getReadPostsOfFriends(String userId, Integer offset, Integer limit) throws NumberFormatException, ParseException {
        //获取好友列表
        ResultMessage<List<User>> data = friendsClient.findFriends();
        List<User> friendsList = data.getData();
        List<CmfPostsListOfFriends> postsList = new ArrayList<CmfPostsListOfFriends>();
        logger.info("============" + friendsList.size());
        if (null != friendsList && friendsList.size() > 0) {
            logger.info("friendsList.size()=" + friendsList.size());
            //获取好友浏览过的新闻
            PageHelper.startPage(offset, limit);
            postsList = cmfPostsMapper.getReadOfFriends(friendsList);
            if (null != postsList && postsList.size() > 0) {
                //获取作者信息
                CmfAuthors authors = new CmfAuthors();
                for (CmfPostsListOfFriends posts : postsList) {
                    Long postId = posts.getId();
                    String newsType = posts.getTpl();
                    posts.setOneTpl(newsType);
                    authors = cmfAuthorService.getAuthorsOfPosts(
                            Integer.valueOf(String.valueOf(posts.getAuthorId())));
                    posts.setAuthors(authors);
                    //获取好友评论
                    ResultMessage<List<Forumcomment>> resultMessage =
                            forumClient.getFrindsCommentInNews(userId, String.valueOf(postId));
                    List<Forumcomment> friendsComment = resultMessage.getData();

                    if (null != friendsComment && friendsComment.size() > 0) {
                        logger.info("friendsComment.size()=" + friendsComment.size());
                        posts.setFriendsComment(friendsComment);
                        posts.setFriendsCommentCount(friendsComment.size());
                    }
                }
            }
        }
        return postsList;
    }

    /**
     * 根据id获取新闻详情
     *
     * @param postId
     * @return
     * @author hexz
     * @date 2017.7.3
     */
    @Transactional
    public CmfPostsDtlVo getPostDetailById(Long postId, String userId) {
        if (null == postId) {
            throw new AppException("文章id不能为空");
        }
        CmfPostsDtlVo cmfPostsDtlVo = cmfPostsMapper.getPostDetailById(postId);
        if (null != cmfPostsDtlVo) {
            //分享链接，详情页链接
            cmfPostsDtlVo.setShareUrl(appConfig.getShareUrl() + "?id=" + postId);
            cmfPostsDtlVo.setDetailUrl(appConfig.getNewsDetailUrl() + "?id=" + postId);
            if (null != userId) {
                //作者信息
                Integer authorId = Integer.valueOf(String.valueOf(cmfPostsDtlVo.getAuthorId()));
                CmfAuthors authors = hasFocusAuthor(authorId, userId);
                cmfPostsDtlVo.setAuthors(authors);
                //判断是否已经点赞
                ResultMessage<Integer> data = forumClient.hasPraised(userId, String.valueOf(postId));
                Integer hasPraised = data.getData();
                cmfPostsDtlVo.setHasPraised(hasPraised);
                //获取文章对应标签
                List<CmfLabel> labels = cmfLabelMapper.getLabelsOfPosts(postId);
                List<String> newsLabels = new ArrayList<String>();
                for (CmfLabel label : labels) {
                    newsLabels.add(label.getLabelTitle());
                }
                cmfPostsDtlVo.setLabels(newsLabels);
                if (StringUtils.isNotEmpty(userId)) {
                    //记录用户浏览记录
                    CmfPostsReadlog cmfPostsReadlog = new CmfPostsReadlog();
                    cmfPostsReadlog.setCreateTime(new Date());
                    cmfPostsReadlog.setPostsId(postId);
                    cmfPostsReadlog.setUserId(userId);
                    cmfPostsReadlog.setPostsReadlogId(StringUUIdUtil.getUUID());
                    cmfPostsReadlogMapper.insert(cmfPostsReadlog);
                    //更新点击量
                    CmfPostsWithBLOBs posts = new CmfPostsWithBLOBs();
                    posts.setId(postId);
                    posts.setPostHits(cmfPostsDtlVo.getPostHits() + 1);
                    cmfPostsMapper.updateByPrimaryKeySelective(posts);
                }
            }
        }
        return cmfPostsDtlVo;
    }

    /**
     * 判断是否已关注作者
     *
     * @param authorId
     * @param userId
     * @return
     */
    private CmfAuthors hasFocusAuthor(Integer authorId, String userId) {
        CmfAuthors authors = cmfAuthorsMapper.getPostsAuthors(authorId);
        if (null != authors) {
            CmfAuthorFocus authorFocus = cmfAuthorFocusMapper.checkIsFocus(authorId, userId);
            authors.setIsFocus(NO_FOCUS);
            if (null != authorFocus) {
                authors.setIsFocus(IS_FOCUS);
            }
        }
        return authors;
    }

    /**
     * 根据关键字获取新闻列表
     *
     * @param keyWords
     * @return
     */
    public List<CmfPostsListVo> getPostsByKeywords(String keyWords, Integer pageSize, Integer lastTime) {
        List<CmfPostsListVo> postsListVos = cmfPostsMapper.getPostByKeywords(keyWords, pageSize, lastTime);
        assemblePosts(postsListVos);
        return postsListVos;
    }

    /**
     * 根据termId批量获取新闻列表
     *
     * @return
     * @author hexz
     * @date 2017.6.28
     */
    public List<CmfPostsListVo> getnewsByTermId(Integer navId, Integer pageSize, String userId) {
        List<CmfPostsListVo> postsListVos = new ArrayList<CmfPostsListVo>();
        //根据导航id获取关系列表
        CmfNav newsNav = cmfNavMapper.selectByPrimaryKey(navId);
        Long termId = 0L;
        if (null != newsNav) {
            termId = newsNav.getTid();
        }
        //执行http接口
        Long startTime = System.currentTimeMillis();
        String result = OkHttpUtils.get(appConfig.getHotNewsUrl())
                .param("userid", userId)
                .param("termid", termId)
                .param("count", pageSize)
                .param("wifi", 0)
                .callForString();
        Long endTime = System.currentTimeMillis();
        logger.info("耗时------------" + (endTime - startTime));
        CmfHotNewsVo hotNewsVo = GsonUtils.toObject(result.trim(), new TypeToken<CmfHotNewsVo>() {
        });
        logger.info("===============" + GsonUtils.toJson(hotNewsVo));
        if (hotNewsVo.getStatus() == 0) {
            return null;
        }
        //热点新闻id列表
        List<Long> hotNewsIds = hotNewsVo.getData().getHot_news();
        logger.info(GsonUtils.toJson(hotNewsIds));
        if (null != hotNewsIds && hotNewsIds.size() > 0) {
            for (Long id : hotNewsIds) {
                CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getRecommendedNews(id);
                cmfPostsListVo.setIsHot("1");
                getNewsList(userId, postsListVos, id, cmfPostsListVo);
            }
        }
        List<Long> postsIdList = new ArrayList<>();
        //推荐新闻id列表
        List<Long> recoNewsIds = hotNewsVo.getData().getRecom_news();
        if (null != recoNewsIds && recoNewsIds.size() > 0) {
            for (Long id : recoNewsIds) {
                CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getRecommendedNews(id);
                cmfPostsListVo.setIsHot("0");
                getNewsList(userId, postsListVos, id, cmfPostsListVo);
            }
        }
        return postsListVos;
    }

    /**
     * 组装新闻List
     *
     * @param userId
     * @param postsListVos
     * @param id
     * @param cmfPostsListVo
     */
    private void getNewsList(String userId, List<CmfPostsListVo> postsListVos, Long id, CmfPostsListVo cmfPostsListVo) {
        if (null != cmfPostsListVo) {
            CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                    Integer.valueOf(String.valueOf(cmfPostsListVo.getAuthorId())));
            String newsType = cmfPostsListVo.getTpl();
            cmfPostsListVo.setOneTpl(newsType);
            cmfPostsListVo.setAuthors(authors);
            if ("article_pics".equals(newsType)) {
                String content = cmfPostsListVo.getPostContent();
                CmfPicturesVo picturesVo = GsonUtils.toObject(content, new TypeToken<CmfPicturesVo>() {
                });
                cmfPostsListVo.setPicturesNum(picturesVo.getImg_counts());
            }
            if (!"article_video".equals(newsType) &&
                    !"article_news_text".equals(newsType)) {
                cmfPostsListVo.setPostContent(null);
            }
            //判断是否已经点赞
            ResultMessage<Integer> data = forumClient.hasPraised(userId, String.valueOf(id));
            Integer hasPraised = data.getData();
            cmfPostsListVo.setHasPraised(hasPraised);
            cmfPostsListVo.setShareUrl(appConfig.getShareUrl() + "?id=" + String.valueOf(id));
            postsListVos.add(cmfPostsListVo);
        }
    }

    /**
     * 获取热评新闻列表
     *
     * @param lastTime
     * @return
     * @throws ParseException
     */
    public List<CmfPostsListVo> getHotCommentNews(Integer pageSize, String lastTime, String userId) {
        List<CmfPostsListVo> postsListVos = new ArrayList<CmfPostsListVo>();
        if (null != lastTime) {
            List<CmfTermRelationships> termRelationships =
                    cmfTermRelationshipsMapper.getTermRelations(lastTime);
            List<CmfTermRelationships> termRels = new ArrayList<CmfTermRelationships>();
            if (null != termRelationships && termRelationships.size() > 0) {
                for (int i = 0; i < pageSize; i++) {
                    Random random = new Random();
                    int index = random.nextInt(termRelationships.size() - 1);
                    termRels.add(termRelationships.get(index));
                }
                postsListVos = cmfPostsMapper.getHotCommentNews(termRels, userId);
                assemblePosts(postsListVos);
            }
        }
        return postsListVos;

    }

    /**
     * 通过id列表获取新闻列表
     *
     * @param ids
     * @return
     */
    public List<CmfPostsListVo> getNewsByIds(List<Long> ids) {
        if ((null == ids)
                || (0 == ids.size())) {
            return null;
        }

        return cmfPostsMapper.getNewsByIds(ids);
    }

    /**
     * 获取用户关注的新闻
     *
     * @return
     */
    public List<CmfPostsListVo> getNewsForHomePage(Integer beforeDeadTime, Integer lastDeadtime, String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new AppException("用户id不能为空");
        }
        //获取关注作者
        List<CmfAuthors> focusAuthors = cmfAuthorService.getFocusAuthors(userId);

        List<CmfPostsListVo> postsListVos = null;
        //获取关注作者的新闻
        if (null != focusAuthors && focusAuthors.size() > 0) {
            if (null != beforeDeadTime) {
                postsListVos = cmfPostsMapper.getFocusNewsBeforeTime(focusAuthors, beforeDeadTime);
                assemblePosts(postsListVos);
                logger.info("=======" + postsListVos.size());
            } else {
                postsListVos = cmfPostsMapper.getFocusNewsAfterTime(focusAuthors, lastDeadtime);
                assemblePosts(postsListVos);
                logger.info("=======" + postsListVos.size());
            }

            List<String> listAuthorName = new ArrayList<String>();
            Iterator<CmfPostsListVo> iterator = postsListVos.iterator();
            while (iterator.hasNext()) {
                CmfPostsListVo vo = iterator.next();
                if (listAuthorName.contains(vo.getAuthors().getName())) {
                    iterator.remove();
                } else {
                    listAuthorName.add(vo.getAuthors().getName());
                }
            }

            if (postsListVos.size() > 2) {
                return postsListVos.subList(0, 2);
            }
            return postsListVos;
        }
        return null;
    }

    /**
     * 组装文章对象属性信息
     *
     * @param postsListVos
     */
    public List<CmfPostsListVo> assemblePosts(List<CmfPostsListVo> postsListVos) {
        if (null != postsListVos && postsListVos.size() > 0) {
            for (CmfPostsListVo postsListVo : postsListVos) {
                if (null != postsListVo) {
                    String newsType = postsListVo.getTpl();
                    CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                            Integer.valueOf(String.valueOf(postsListVo.getAuthorId())));
                    postsListVo.setOneTpl(newsType);
                    postsListVo.setAuthors(authors);
                    if ("article_pics".equals(newsType)) {
                        String content = postsListVo.getPostContent();
                        CmfPicturesVo picturesVo = new Gson().fromJson(content, new TypeToken<CmfPicturesVo>() {
                        }.getType());
                        postsListVo.setPicturesNum(picturesVo.getImg_counts());
                    }
                    if (!"article_video".equals(newsType) &&
                            !"article_news_text".equals(newsType)) {
                        postsListVo.setPostContent(null);
                    }
                }
            }
        }
        return postsListVos;
    }

    /**
     * 分页搜索视频
     *
     * @param keyWords
     * @param offset
     * @param limit    kanghulin@qq.com
     * @return
     */
    public List<CmfPostsListVo> searchForVideos(String keyWords, Integer offset, Integer limit) {
        PageHelper.startPage(offset, limit);
        List<CmfPostsListVo> videoList =
                cmfPostsMapper.searchForVideos("article_video", keyWords);
        //组装作者信息
        for (CmfPostsListVo videos : videoList) {
            CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                    Integer.valueOf(String.valueOf(videos.getAuthorId())));
            videos.setAuthors(authors);
        }
        return videoList;
    }

    /**
     * 获取趣视频
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<CmfVideoListVo> getJokeVideoList(Integer navId, Integer offset, Integer limit, String keyWords) {
        List<CmfTermRelationships> termRelationships = new ArrayList<CmfTermRelationships>();
        //获取推荐趣视频
        if (0 == navId) {
            //获取所有视频子栏目
            List<CmfTerms> termsList = cmfTermsMapper.getVideosTerms();
            for (CmfTerms terms : termsList) {
                List<CmfTermRelationships> termRels =
                        cmfTermRelationshipsMapper.getTermRelationships(terms.getTermId());
                termRelationships.addAll(termRels);
            }
            PageHelper.startPage(offset, limit);
            return cmfPostsMapper.getRecommendedJokeVideos(termRelationships, keyWords);
        }
        //按栏目获取
        termRelationships = cmfTermRelationshipsMapper.getTermRelationships(
                cmfNavMapper.selectByPrimaryKey(navId).getTid());
        logger.info("termRelationships.size()===" + termRelationships.size());
        if (null == termRelationships || termRelationships.size() < 1) {
            throw new AppException("未获取到趣视频");
        }
        PageHelper.startPage(offset, limit);
        return cmfPostsMapper.getJokeVideos(termRelationships, keyWords);
    }

    /**
     * 更新评论数
     *
     * @param postsId
     * @return
     */
    @Transactional
    public int updateCommentCount(Long postsId, String updateType) {

        CmfPostsDtlVo postsDtlVo = cmfPostsMapper.getPostDetailById(postsId);
        if (null == postsDtlVo) {
            throw new AppException("新闻信息获取异常");
        }
        Long commentCount = postsDtlVo.getCommentCount();
        CmfPostsWithBLOBs posts = new CmfPostsWithBLOBs();
        posts.setId(postsId);
        if ("0".equals(updateType)) {
            posts.setCommentCountShow(commentCount + 1);
        } else {
            posts.setCommentCountShow(commentCount - 1);
        }
        return cmfPostsMapper.updateByPrimaryKeySelective(posts);
    }

    /**
     * 更新点赞数
     *
     * @param postsId
     * @return
     */
    @Transactional
    public int updatePostLikes(Long postsId, String likesType) {

        CmfPostsDtlVo postsDtlVo = cmfPostsMapper.getPostDetailById(postsId);
        if (null == postsDtlVo) {
            throw new AppException("新闻信息获取异常");
        }
        Integer postLikes = postsDtlVo.getPostLike();
        CmfPostsWithBLOBs posts = new CmfPostsWithBLOBs();
        posts.setId(postsId);
        if ("0".equals(likesType)) {
            posts.setPostLike(postLikes + 1);
        } else {
            //取消点赞
            posts.setPostLike(postLikes - 1);
        }
        return cmfPostsMapper.updateByPrimaryKeySelective(posts);
    }

    /**
     * 趣闻推荐(弃用)
     *
     * @param pageSize
     * @return
     */
    public Map<String, Object> getJokes(Integer pageSize, String lastTime, String userId) {
        if (null == pageSize) {
            throw new AppException("指定条数不能为空");
        }
        if (StringUtils.isEmpty(userId)) {
            throw new AppException("用户名不能为空");
        }
        Map<String, Object> jokes = new HashMap<String, Object>();
        List<CmfTermRelationships> termRelationships =
                cmfTermRelationshipsMapper.getTermRelationships(52L);
        if (null == termRelationships || termRelationships.size() < 1) {
            throw new AppException("未获取到趣闻");
        }
        //获取后台系统用户信息,是否被屏蔽
        ResultMessage<Boolean> data = forumClient.hasShield(userId, JOKE_RECOMMENEDE);
        if (!data.getData()) {
            List<CmfPostsListVo> cmfpostslistvo =
                    cmfPostsMapper.searchForJokes(termRelationships, 10);
            List<CmfPostsDtlVo> jokeDtl = new ArrayList<CmfPostsDtlVo>();
            //随机取指定条数
            for (int i = 0; i < pageSize; i++) {
                Random random = new Random();
                int index = random.nextInt(9);
                CmfPostsDtlVo postDetail = new CmfPostsDtlVo();
                postDetail = cmfPostsMapper.getPostDetailById(cmfpostslistvo.get(index).getId());
                //获取作者来源信息
                CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                        Integer.valueOf(String.valueOf(cmfpostslistvo.get(index).getAuthorId())));
                postDetail.setAuthors(authors);
                jokeDtl.add(postDetail);
            }
            ResultMessage<User> userData = userFeignClient.getUser(JOKE_RECOMMENEDE);
            jokes.put("user", userData.getData());
            jokes.put("joke", jokeDtl);
        }
        return jokes;
    }

    /**
     * 首页获取热评新闻
     *
     * @param pageSize
     * @return
     * @throws IOException
     */
    public Map<String, Object> getHotNewsForHomePage(Integer pageSize, String userId) {
        if (null == pageSize) {
            throw new AppException("指定条数不能为空");
        }
        Map<String, Object> hotNews = new HashMap<String, Object>();
        //获取后台系统用户信息,是否被屏蔽
        ResultMessage<Boolean> data = forumClient.hasShield(userId, HOT_COMMENT_NEWS);
        if (!data.getData()) {
            //获取推荐新闻及系统用户信息
            String result = OkHttpUtils.get(appConfig.getRecommendedNewsUrl())
                    .param("userid", userId)
                    .param("count", pageSize)
                    .param("wifi", 1)
                    .callForString();
            if (StringUtils.isEmpty(result)) {
                return null;
            }
            CmfRecommendedNewsVo recommendedNewsVo =
                    GsonUtils.toObject(result, new TypeToken<CmfRecommendedNewsVo>() {
                    });
            if (recommendedNewsVo.getStatus() == 0) {
                return null;
            }
            List<Long> postsIdList = recommendedNewsVo.getData().getRecom_news();
            List<CmfPostsListVo> postsListVos = new ArrayList<CmfPostsListVo>();
            if (postsIdList != null && postsIdList.size() > 0) {
                for (Long id : postsIdList) {
                    CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getRecommendedNews(id);
                    if (null != cmfPostsListVo) {
                        postsListVos.add(cmfPostsListVo);
                    }
                }
            }
            logger.info("size=========" + postsListVos.size());
            assemblePosts(postsListVos);
            ResultMessage<User> userData = userFeignClient.getUser(HOT_COMMENT_NEWS);
            hotNews.put("user", userData.getData());
            hotNews.put("news", postsListVos);
        }
        return hotNews;
    }

    /**
     * 获取推荐新闻
     *
     * @param userId
     * @param pageSize
     * @return
     * @throws IOException
     */
    public List<CmfPostsListVo> getRecommendedNews(String userId, Integer pageSize) {
        if (StringUtils.isEmpty(userId)) {
            throw new AppException("用户id不能为空");
        }
        if (null == pageSize) {
            throw new AppException("获取总数不能为空");
        }
        //执行http接口(Python提供)
        String result = OkHttpUtils.get(appConfig.getRecommendedNewsUrl())
                .param("userid", userId)
                .param("count", pageSize)
                .param("wifi", 1)
                .callForString();
        if (StringUtils.isEmpty(result)) {
            return null;
        }
        CmfRecommendedNewsVo recommendedNewsVo =
                GsonUtils.toObject(result, new TypeToken<CmfRecommendedNewsVo>() {
                });
        if (recommendedNewsVo.getStatus() == 0) {
            return null;
        }
        List<Long> postsIdList = new ArrayList<>();
        //热点新闻id列表
        List<Long> hotNewsIds = recommendedNewsVo.getData().getHot_news();
        logger.info(GsonUtils.toJson(hotNewsIds));
        List<CmfPostsListVo> postsListVos = new ArrayList<CmfPostsListVo>();
        if (null != hotNewsIds && hotNewsIds.size() > 0) {
            for (Long id : hotNewsIds) {
                CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getRecommendedNews(id);
                cmfPostsListVo.setIsHot("1");
                getNewsList(userId, postsListVos, id, cmfPostsListVo);
            }
        }
        //推荐新闻id列表
        List<Long> recoNewsIds = recommendedNewsVo.getData().getRecom_news();
        if (null != recoNewsIds && recoNewsIds.size() > 0) {
            for (Long id : recoNewsIds) {
                CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getRecommendedNews(id);
                cmfPostsListVo.setIsHot("0");
                getNewsList(userId, postsListVos, id, cmfPostsListVo);
            }
        }
        return postsListVos;
    }

//    /**
//     * 用户注册初始化权值
//     *
//     * @param gender
//     * @param bornDate
//     */
//    @Transactional
//    public void initUserWeight(String userId, Integer gender, Long bornDate) {
//        User user = userFeignClient.getUser(userId).getData();
//        gender = (null == gender) ? user.getGender() : gender;
//        bornDate = (null == bornDate) ? user.getBornDate().getTime() : bornDate;
//        //已有记录不再初始化
//        CmfAuthorWeightWithBLOBs cmfAuthorWeightWithBLOBs = cmfAuthorWeightMapper.getRecordByUserId(userId);
//        if (null != cmfAuthorWeightWithBLOBs) {
//            return;
//        }
//        //初始化权值字典
//        HashMap<Integer, Integer> weighMap = initByGenderAndAge(gender, bornDate);
//        //记录到权值表
//        CmfAuthorWeightWithBLOBs userWeight = new CmfAuthorWeightWithBLOBs();
//        userWeight.setUserId(userId);
//        userWeight.setTermWeight(GsonUtil.GsonString(weighMap).trim().replace("\"", ""));
//        cmfAuthorWeightMapper.insert(userWeight);
//
//        //同步到redis
//        String weight = "{},{}," + GsonUtil.GsonString(
//                weighMap).replace("\"", "").replace("\n", "").trim();
//        //字符串序列化
//        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//        redisTemplate.setHashKeySerializer(stringRedisSerializer);
//        redisTemplate.setHashValueSerializer(stringRedisSerializer);
//        redisTemplate.opsForHash().put("user_weight", userId, weight);
//    }

    /**
     * 获取相关联的新闻列表
     *
     * @param pageSize
     * @param userId
     * @return
     */
    public List<CmfPostsListVo> getRelationNews(Long postId, Integer pageSize, String userId, Integer type) {

        List<CmfPostsListVo> cmfVideoListVos = new ArrayList<CmfPostsListVo>();
        //获取相关视频，需要第一条是自己
        if (1 == type) {
            CmfPostsListVo cmfPostsListVo = cmfPostsMapper.getVideoDetailById(postId);
            //作者信息
            Integer authorId = Integer.valueOf(String.valueOf(cmfPostsListVo.getAuthorId()));
            CmfAuthors authors = hasFocusAuthor(authorId, userId);
            cmfPostsListVo.setAuthors(authors);
            //判断是否已经点赞
            ResultMessage<Integer> data = forumClient.hasPraised(
                    userId, String.valueOf(cmfPostsListVo.getId()));
            Integer hasPraised = data.getData();
            cmfPostsListVo.setHasPraised(hasPraised);
            cmfPostsListVo.setShareUrl(appConfig.getShareUrl() + "?id=" + String.valueOf(postId));
            cmfVideoListVos.add(cmfPostsListVo);
            //记录用户浏览记录
            CmfPostsReadlog cmfPostsReadlog = new CmfPostsReadlog();
            cmfPostsReadlog.setCreateTime(new Date());
            cmfPostsReadlog.setPostsId(postId);
            cmfPostsReadlog.setUserId(userId);
            cmfPostsReadlog.setPostsReadlogId(StringUUIdUtil.getUUID());
            cmfPostsReadlogMapper.insert(cmfPostsReadlog);
            //更新点击量
            CmfPostsWithBLOBs posts = new CmfPostsWithBLOBs();
            posts.setId(postId);
            posts.setPostHits(cmfPostsListVo.getPostHits() + 1);
            cmfPostsMapper.updateByPrimaryKeySelective(posts);
        }
        //获取对应栏目
        CmfTermRelationships cmfTermRelationships = cmfTermRelationshipsMapper.getTremsRelByPostId(postId);
        //根据栏目获取视频
        String result = OkHttpUtils.get(appConfig.getRelationNewsUrl())
                .param("userId", userId).param("channelid", cmfTermRelationships.getTermId())
                .param("newsid", postId).param("count", pageSize).param("history", 1)
                .param("unique", 1).callForString();
        CmfRecoNewsVo cmfRelationNews = GsonUtils.toObject(result, new TypeToken<CmfRecoNewsVo>() {
        });
        if (cmfRelationNews.getStatus() == 0 && 1 == type) {
            return cmfVideoListVos;
        }
        if (cmfRelationNews.getStatus() == 0 && 2 == type) {
            return null;
        }

        for (Long id : cmfRelationNews.getResult()) {
            CmfPostsListVo postDetail = cmfPostsMapper.getRecommendedNews(id);
            //是视频时过滤非视频新闻
            if (1 == type && !"article_video".equals(postDetail.getTpl())) {
                continue;
            }
            if (null != postDetail) {
                Integer authorId = Integer.valueOf(String.valueOf(postDetail.getAuthorId()));
                CmfAuthors authors = hasFocusAuthor(authorId, userId);
                postDetail.setAuthors(authors);
                //判断是否已经点赞
                ResultMessage<Integer> data = forumClient.hasPraised(
                        userId, String.valueOf(postDetail.getId()));
                Integer hasPraised = data.getData();
                postDetail.setHasPraised(hasPraised);
                postDetail.setShareUrl(appConfig.getShareUrl() + "?id=" + String.valueOf(id));
                cmfVideoListVos.add(postDetail);
            }
        }
        return cmfVideoListVos;
    }

    /**
     * 根据ID获取新闻列表
     *
     * @param id
     * @return
     */
    public CmfPostsListVo getPostsListById(Long id) {
        CmfPostsListVo postsListVo = cmfPostsMapper.getPostsListById(id);
        if (postsListVo != null) {
            String newsType = postsListVo.getTpl();
            CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                    Integer.valueOf(String.valueOf(postsListVo.getAuthorId())));
            postsListVo.setOneTpl(newsType);
            postsListVo.setAuthors(authors);
        }
        return postsListVo;
    }

    /**
     * 获取热闻推荐
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<CmfPostsListVo> getImportantNews(Integer offset, Integer limit, String userId) {
        //执行http接口
        String result = OkHttpUtils.get(appConfig.getImportantNewsUrl())
                .param("page", offset)
                .param("count", limit)
                .callForString();

        List<CmfPostsListVo> postsListVos = new ArrayList<CmfPostsListVo>();
        if (StringUtils.isNotEmpty(result)) {
            //解析返回值
            CmfImportantNewsVo importantNewsVo = GsonUtils.toObject(result, new TypeToken<CmfImportantNewsVo>() {
            });
            if (importantNewsVo.getStatus() == 1) {

                for (Long id : importantNewsVo.getResult()) {
                    CmfPostsListVo cmfPostsListVo =
                            cmfPostsMapper.getRecommendedNews(id);
                    if (null != cmfPostsListVo) {
                        CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                                Integer.valueOf(String.valueOf(cmfPostsListVo.getAuthorId())));
                        String newsType = cmfPostsListVo.getTpl();
                        cmfPostsListVo.setOneTpl(newsType);
                        cmfPostsListVo.setAuthors(authors);
                        //图片新闻解析图片数量
                        if ("article_pics".equals(newsType)) {
                            String content = cmfPostsListVo.getPostContent();
                            CmfPicturesVo picturesVo = new Gson().fromJson(content, new TypeToken<CmfPicturesVo>() {
                            }.getType());
                            cmfPostsListVo.setPicturesNum(picturesVo.getImg_counts());
                        }
                        //判断是否已读
                        cmfPostsListVo.setHasRead("0");
                        List<CmfPostsReadlog> readlogs = cmfPostsReadlogMapper.getReadLog(userId, id);
                        if (readlogs != null && readlogs.size() > 0) {
                            cmfPostsListVo.setHasRead("1");
                        }
                        postsListVos.add(cmfPostsListVo);
                    }
                }
            }
        }
        return postsListVos;
    }

    /**
     * 获取热门视频
     *
     * @param userId
     * @param count
     * @return
     */
    public List<CmfPostsListVo> getHotVideos(String userId, Integer count) {
        if (StringUtils.isEmpty(userId)) {
            throw new AppException("userId不能为空");
        }
        //执行http接口
        String result = OkHttpUtils.get(appConfig.getHotVideosUrl())
                .param("userid", userId)
                .param("count", count)
                .callForString();
        CmfRecoNewsVo cmfHotVideosVo = GsonUtils.toObject(result, new TypeToken<CmfRecoNewsVo>() {
        });
        //查询视频列表
        List<CmfPostsListVo> postsListVos = new ArrayList<>();
        if (cmfHotVideosVo.getStatus() == 1) {

            for (Long id : cmfHotVideosVo.getResult()) {
                CmfPostsListVo cmfPostsListVo =
                        cmfPostsMapper.getRecommendedNews(id);
                if (null != cmfPostsListVo) {
                    //作者信息
                    CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                            Integer.valueOf(String.valueOf(cmfPostsListVo.getAuthorId())));
                    String newsType = cmfPostsListVo.getTpl();
                    cmfPostsListVo.setOneTpl(newsType);
                    cmfPostsListVo.setAuthors(authors);
                    //判断是否已经点赞
                    ResultMessage<Integer> data = forumClient.hasPraised(
                            userId, String.valueOf(id));
                    Integer hasPraised = data.getData();
                    cmfPostsListVo.setHasPraised(hasPraised);
                    cmfPostsListVo.setShareUrl(appConfig.getShareUrl() + "?id=" + String.valueOf(id));
                    postsListVos.add(cmfPostsListVo);
                }
            }
        }
        return postsListVos;
    }

    /**
     * 获取推荐趣视频
     *
     * @param offset
     * @param limit
     * @return
     */
    public List<CmfPostsListVo> getRecommendedVideos(Integer offset, Integer limit) {
        PageHelper.startPage(offset, limit);
        List<CmfPostsListVo> videos = cmfPostsMapper.getRecommendedVideos();
        if (null != videos && videos.size() > 0) {
            for (CmfPostsListVo video : videos) {
                //作者信息
                CmfAuthors authors = cmfAuthorService.getAuthorsOfPosts(
                        Integer.valueOf(String.valueOf(video.getAuthorId())));
                String newsType = video.getTpl();
                video.setOneTpl(newsType);
                video.setAuthors(authors);
            }
        }
        return videos;
    }

    /**
     * 获取最新评论数
     *
     * @param ids
     * @return
     */
    public List<CmfCommentCountVo> reloadCommentCount(String ids) {
        if (StringUtils.isEmpty(ids)) {
            throw new AppException("新闻id不能为空");
        }

        List<Long> idList = GsonUtils.toObject(ids, new TypeToken<List>() {
        });
        List<CmfCommentCountVo> commentCount = new ArrayList<>();
        if (null != idList && idList.size() > 0) {
            commentCount = cmfPostsMapper.reloadCommentCount(idList);
        }
        return commentCount;
    }

    /**
     * PC后台按标题检索新闻
     *
     * @param lastTime
     * @param pageSize
     * @param keywords
     * @return
     */
    public List<CmfFindNewsVo> findNewsByKeywords(Integer lastTime, Integer pageSize, String keywords) {
        if (pageSize == null) {
            throw new AppException("分页参数不能为空！");
        }
        if (StringUtils.isNotEmpty(keywords)) {
            return cmfPostsMapper.findNewsByKeywords(keywords, lastTime, pageSize);
        }
        return null;
    }

}
